package rclient
import(
	"github.com/lesismal/arpc"
	"gintest/core/consul"
	"time"
	"net"
	"strconv"
	"errors"
)
var rpcClient map[string]*arpc.Client
func Init(){
	rpcClient=make(map[string]*arpc.Client)
}
func Close(){
	for _, v := range rpcClient {
        v.Stop()
    }
}
func Call(name string,param string) string{
	var str string
	var err error
	for i:=0;i<5;i++{
		str,err=client(name,param)
		if err!=nil{
			if _, ok := rpcClient[name]; ok {
				rpcClient[name].Stop()
				delete(rpcClient,name)
			}
		}else{
			break
		}
		
	}
	return str
}
func client(name string,param string) (string,error){
	if _, ok := rpcClient[name]; !ok {
		cfg:=consul.BuildByName(name)
		if(cfg==nil){
			return "",errors.New("error")
		}
		client, err := arpc.NewClient(func() (net.Conn, error) {
			return net.DialTimeout("tcp", cfg.Host+":"+strconv.Itoa(cfg.Port), time.Second*3)
		})
		if err != nil {
			return "",errors.New("error")
		}
		rpcClient[name]=client

		client.Run()
	}

	rsp := ""
	err := rpcClient[name].Call(name, &param, &rsp, time.Second*5)
	if err != nil {
		return "",errors.New("error")
	} else {
		return rsp,nil
	}
	
}